<template>
    <div>
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card class="box-card">
        <!-- 搜索区域 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input clearable @clear="getUserList" v-model="queryData.query" placeholder="请输入内容" class="input-with-select">
              <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <!-- 添加按钮 -->
          <el-col :span="4">
            <el-button @click="addUserDialogVisible=true" type="primary">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表表格 -->
        <el-table :data="users" style="width: 100%" border stripe>
          <!-- prop：用来指定渲染的字段名    -->
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch @change="changeSwitch(scope.row)" v-model="scope.row.mg_state">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <!-- 编辑 -->
              <el-button @click="editUser(scope.row)" type="primary" icon="el-icon-edit" size="mini"></el-button>
              <!-- 删除 -->
              <el-button @click="removeUser(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
              <!-- 分配角色 -->
              <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
                <el-button @click="setRole(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryData.pagenum"
          :page-sizes="[2, 4, 8, 10]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
      <!-- 添加用户对话框 -->
      <el-dialog
        @close="addUserClose"
        title="添加用户"
        :visible.sync="addUserDialogVisible"
        width="50%">
        <!-- 主体内容 -->
        <el-form ref="addUserForm" :model="addUserForm" :rules="addUserRules" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 对话框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subAddUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog
        @close="editFormClose"
        title="修改用户"
        :visible.sync="editUserDialogVisible"
        width="50%">
        <el-form ref="editUserForm" :model="editForm" :rules="addUserRules" label-width="80px">
          <el-form-item label="用户名：">
            <el-input disabled v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subEditUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话款 -->
      <el-dialog
        @close="closeSetRole()"
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%">
        <div>
          <p>当前的用户：{{ userInfo.username }}</p>
          <p>当前的角色：{{ userInfo.role_name }}</p>
          <div>
            分配新角色：
            <!-- v-model:  既可以设置默认选中，也可以保存选中的值-->
            <el-select v-model="selectValue" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subSetRoles()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    // 定义邮箱的校验规则
    const checkEmail = (rule,value,cb) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      // 如果符合正则条件 直接cb()
      if(reg.test(value)) return cb()
      cb(new Error('邮箱格式不正确'))
    }
    // 定义手机号的校验规则
    const checkMobile = (rule,value,cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      // 如果符合正则条件 直接cb()
      if(reg.test(value)) return cb()
      cb(new Error('手机格式不正确'))
    }
    return {
      // 获取用户列表数据的参数
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表
      users: [],
      // 总条数
      total: 0,
      // 控制添加用户对话框显示隐藏
      addUserDialogVisible: false,
      // 添加用户表单数据
      addUserForm: {
        username: '坤坤',
        password: '123456',
        email: '123@123.com',
        mobile: '18788880000'
      },
      // 校验添加用户表单的校验规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制编辑用户对话框显示隐藏
      editUserDialogVisible: false,
      // 编辑用户表单数据
      editForm: {},
      // 控制分配角色对话框
      setRoleDialogVisible: false,
      // 分配角色用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // select选择器双向绑定的值
      selectValue: ''
    }
  },

  created() {
    this.getUserList()
  },

  methods: {
    // 获取用户列表数据
    async getUserList () {
      const { data: res } = await this.$axios.get('users',{
        params: this.queryData
      })
      if(res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.users = res.data.users
      this.total = res.data.total
    },
    // 当修改了每页多少条时触发
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 页码发生变化触发
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUserList()
    },
    // 当开关发生变化时触发
    async changeSwitch (userInfo) {
      // 开关发生变化，发送请求同步数据库的数据
      // 用户id:userInfo.id 当前用户的状态值 :userInfo.mg_state
      const {data: res} = await this.$axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(res.meta.status !== 200){
        this.$message.error('修改失败')
        // 修改失败再让开关回到原来二点状态
        userInfo.mg_state = !userInfo.mg_state
        return
      }
      this.$message.success('修改成功')
    },
    // 关闭添加用户对话框
    addUserClose () {
      this.$refs.addUserForm.resetFields()
    },
    // 添加用户
    subAddUser () {
      this.$refs.addUserForm.validate(async flag=>{
        if(!flag) return 
        const {data: res} = await this.$axios.post('users',this.addUserForm)
        if(res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.addUserDialogVisible = false
        this.getUserList()
      })
    },
    // 点击编辑用户
    async editUser (row) {
      const { data: res} = await this.$axios.get('users/'+row.id)
      if(res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.editForm = res.data
      this.editUserDialogVisible = true
    },
    // 监听关闭修改用户对话框
    editFormClose () {
      this.$refs.editUserForm.resetFields()
    },
    // 提交修改用户
    subEditUser () {
      this.$refs.editUserForm.validate(async flag=>{
        if(!flag) return 
        const {data: res} = await this.$axios.put(`users/${this.editForm.id}`,{
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if(res.meta.status !== 200) return this.$message.error('请求失败')
        this.$message.success('请求成功')
        this.editUserDialogVisible = false 
        this.getUserList()
      })
    },
    // 删除用户
    removeUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`users/${id}`)
        if(res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getUserList()
      }).catch(() => {
        this.$message('已取消删除');          
      });
    },
    // 点击分配角色
    async setRole (row) {
      this.userInfo = row
      const {data: res} = await this.$axios.get('roles')
      if(res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 提交分配角色
    async subSetRoles () {
      if(this.selectValue === '') return this.$message.error('亲，请选择角色呦')
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`,{
        rid: this.selectValue
      })
      if(res.meta.status !== 200) return this.$message.error('亲，分配失败了呦')
      this.$message.success('亲，分配成功了呦')
      this.setRoleDialogVisible = false 
      this.getUserList()
    },
    // 监听分配角色对话框关闭
    closeSetRole () {
      this.selectValue = ''
    }
  }
};
</script>

<style scoped lang='less'>

</style>
